<template>
  <a-modal class="reqh" title="新增公告" v-model="show" :maskClosable="false" :width="1400" placement="right"
    :closable="true" @cancel="onClose" :footer="null" :visiable="roleAddVisiable">
    <a-form :form="form">
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='公告标题' v-bind="formItemLayout">
            <a-input v-decorator="['title', { rules: [{ required: true, message: '公告标题不能为空' }] }]" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='公告开始期' v-bind="formItemLayout">
            <a-date-picker placeholder="请选择日期" name="reconFile1" style="width: 100%;"
              v-decorator="['beginTime', validatorRules.beginTime]" format="YYYYMMDD" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='公告有效期' v-bind="formItemLayout">
            <a-date-picker placeholder="请选择日期" name="reconFileDate" style="width: 100%;"
              v-decorator="['expireTime', validatorRules.expireTime]" format="YYYYMMDD" />
          </a-form-item>
        </a-col>

        <a-col :md="12" :sm="24">
          <a-form-item label='公告内容' v-bind="formItemLayout">
            <a-textarea v-decorator="['message', { rules: [{ required: true, message: '请输入公告内容' }] }]" allow-clear />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='商户号' v-bind="formItemLayout">
            <a-textarea v-decorator="['circleList']" :dataSource="batchDataSource" warp="hard" allow-clear />
            <!-- <a @click="circleli" type="primary">确定</a> -->
            <h5> 请输入商户号，一行一个，最多输入1000个<br />
              已录入{{ this.notity.remark1 }}个商户号</h5>
            <!-- <span style="color: #0065ff;" @click="exportExcel">导入</span> -->
            <span style="color: #0065ff;" @click="getExcelTemplate()">下载导入模板</span>
            <span>
              <a-upload :fileList="fileList" :beforeUpload="beforeUpload" style="margin: 0px;" @change="handleChange"
                :disabled="fileList.length === 1" :loading="uploading">
                <a-button style="color: #0065ff; border:none">
                  导入
                </a-button>
              </a-upload>
            </span>

            <p></p>
          </a-form-item>
        </a-col>
        <a-col class="components" :md="12" :sm="24">
          <a @click="circleli" type="primary">确定</a>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='商圈号' v-bind="formItemLayout">
            <a-textarea v-decorator="['merchantList']" allow-clear />
            <h5> 请输入商圈编号，一行一个，最多输入10个<br />
              已录入{{ this.notity.remark2 }}个商圈</h5>
            <p> </p>
          </a-form-item>
        </a-col>
        <a-col class="components" :md="12" :sm="24">
          <a @click="mchnt" type="primary">确定</a>
        </a-col>
      </a-row>
    </a-form>
    <div class="drawer-bootom-button">
      <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>
  </a-modal>
</template>
<script>
//表单位置
import moment from 'moment';
const formItemLayout = {
  labelCol: {
    span: 5
  },
  wrapperCol: {
    span: 14
  }
}
export default {
  name: 'NotityInfoAdd',
  props: {
    roleAddVisiable: {
      default: false
    },
    roleInstId: '',
    roleCodeData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      menuTreeKey: new Date(),
      loading: false,
      formItemLayout,
      form: this.$form.createForm(this),
      validateStatus: '',
      menuSelectStatus: '',
      help: '',
      menuSelectHelp: '',
      // 导入excel时的icon图标
      uploadIcon: 'to-top',
      // 导入excel时是否禁用上传按钮
      uploadDisabled: false,
      notity: {
        instId: this.roleInstId,
        title: '',
        beginTime: '',
        expireTime: '',
        message: '',
        circleList: '',
        merchantList: '',
        remark1: 0,
        remark2: 0
      },
      checkedKeys: [],
      expandedKeys: [],
      menuTreeData: [],
      allTreeKeys: [],
      checkStrictly: false,

      batchDataSource: [],
      // selectCircleInfo: {},
      fileList: [],
      uploading: null,
      validatorRules: {
        beginTime: {
          rules: [
            { required: true, message: '请输入公告开始日期' },
            { trigger: 'change', validator: this.validateBeginTime }

          ]
        },
        expireTime: {
          rules: [
            { required: true, message: '请输入公告有效期' },
            { trigger: 'change', validator: this.validateExpireTime }
          ]
        },
      }
    }
  },
  computed: {
    show: {
      get: function () {
        return this.roleAddVisiable
      },
      set: function () { }
    }
  },
  methods: {
    validateExpireTime(rule, value, cb) {
      const beginTime = moment(this.form.getFieldValue('beginTime')).format('YYYYMMDD')
      const expireTime = moment(value).format('YYYYMMDD')
      if (expireTime < beginTime) {
        cb(new Error('公告有效期应晚于公告开始期'))
      } else {
        cb()
      }
    },
    validateBeginTime(rule, value, cb) {
      if (this.form.getFieldValue('expireTime')) {
        const expireTime = moment(this.form.getFieldValue('expireTime')).format('YYYYMMDD')
        const beginTime = moment(value).format('YYYYMMDD')
        if (beginTime > expireTime) {
          cb(new Error('生效日期应该早于失效日期'))
        } else {
          cb()
        }
      } else {
        cb()
      }
    },

    getExcelTemplate() {
      this.$export('gen/tbnotifyinfo/getExcelTemplate').then(res => {
        console.log(res);
      })
    },
    reset() {
      this.menuTreeKey = +new Date()
      this.expandedKeys = this.checkedKeys = []
      this.validateStatus = ''
      this.expireTimeStatus = ''
      this.expireTimehelp = ''
      this.loading = false
      this.form.resetFields()
    },
    /**
     * 自定义导入文件方法
     * @param data 上传的 excel 文件
     */
    customRequest(data) {
      const file = data.file; // 需要上传的 excel 文件
      let formData = new FormData();
      formData.append('file', file);
      data.onProgress();
      this.$post('gen/tbnotifyinfo/import', file).then(res => {
        if (res) {
          this.$message.success('导入成功');
        } else {
          this.$message.error('导入失败');
        }
      }).finally(() => {
        this.switchIconAndStatus(false);
      });
    },
    switchIconAndStatus(flag) {
      if (flag) {
        this.uploadIcon = 'loading';
        this.uploadDisabled = true;
      } else {
        this.uploadIcon = 'to-top';
        this.uploadDisabled = false;
      }
    },
    onClose() {
      this.reset()
      this.$emit('close')
    },
    expandAll() {
      this.expandedKeys = this.allTreeKeys
    },
    closeAll() {
      this.expandedKeys = []
    },
    circle() {
      this.help = '公告标题不能为空'
    },
    handleCheck(checkedKeys) {
      this.checkedKeys = checkedKeys
      let checkedArr = Object.is(checkedKeys.checked, undefined) ? checkedKeys : checkedKeys.checked
      if (checkedArr.length) {
        this.menuSelectStatus = ''
        this.menuSelectHelp = ''
      } else {
        this.menuSelectStatus = 'error'
        this.menuSelectHelp = '请选择相应的权限'
      }
    },

    handleExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
    },
    secircle() {
      let values = this.form.getFieldsValue(['circleList', 'merchantList'])
      if (typeof values !== 'undefined') {
        Object.keys(values).forEach(_key => {
          this.notity[_key] = values[_key]
        })
      }
    },
    //吧表单上的值放到notity对象里面去
    setRoleFields() {
      let values = this.form.getFieldsValue(['expireTime', 'title', 'beginTime', 'message', 'circleList',
        'merchantList', 'instId'
      ])
      if (typeof values !== 'undefined') {

        Object.keys(values).forEach(_key => {
          if ("beginTime" == _key) {
            if (values[_key].constructor == String) {
              this.notity.beginTime = values.beginTime;
            } else {
              this.notity.beginTime = values.beginTime.format('YYYYMMDD');
            }
          } else if ("expireTime" == _key) {
            if (values[_key].constructor == String) {
              this.notity.expireTime = values.expireTime;
            } else {
              this.notity.expireTime = values.expireTime.format('YYYYMMDD');
            }
          } else if ("instId" == _key) {
            //在公告首页拿法人号赋值到本页面的法人号
            this.notity[_key] = this.roleInstId
          } else {
            this.notity[_key] = values[_key]
          }
        })
      }
    },
    circleli() {
      this.secircle()

      this.$post('gen/tbnotifyinfo/circle', this.notity).then((r) => {
        if (r.data == "") {
          circle = '没有找到该商户'
          this.notity.circleList = ''
        } else {
          this.$message.success("录入商户成功")

          this.notity.remark1 = r.data.remark1
        }
      })
    },
    mchnt() {
      this.secircle()

      this.$post('gen/tbnotifyinfo/Merchant', this.notity).then((r) => {
        if (r.data == "") {
          circle = '没有找到该商圈'
          this.notity.circleList = ''
        } else {
          console.log(this.notity)
          this.$message.success("录入商圈成功")
          this.notity.remark2 = r.data.remark2
        }
      })
    },
    exportExcel() {
      // this.secircle()
      // this.dataSource=this.notity.circleList
      // this.selectCircleInfo=this.notity.circleList
      // console.log(this.selectCircleInfo)
      // debugger
      // let {filteredInfo} = this
      // this.$export('gen/tbnotifyinfo/excel', {
      //   ...this.notity
      //   // ...filteredInfo
      // })


    },

    getAllMerchant() {
      this.$get('gen/tbnotifyinfo/getAllMerchant');
    },

    handleChange: function () {
      const { fileList } = this
      const formData = new FormData()
      formData.append('file', fileList[0])
      this.uploading = true
      this.$upload('gen/tbnotifyinfo/uploadntc', formData).then((r) => {
        console.log(r);
        let data = r.data.data

        this.importData = data.data
        this.errors = data.error
        this.times = data.time / 1000
        this.uploading = false
        this.fileList = []
        this.importResultVisible = true

        if (r.data.data.errorData != null) {
          let errorMessage = "";
          for (let index = 0; index < r.data.data.errorData.length; index++) {
            errorMessage = errorMessage + r.data.data.errorData[index].mchntNo + ",";
          }
          this.$message.error("录入的商圈/商户编号：" + errorMessage + "存在错误，请重新输入！");
        } else {
          for (let index = 0; index < r.data.data.successData.length; index++) {
            this.notity.merchantList.push(r.data.data.successData[index]);
          }
        }
      }).catch((r) => {
        console.error(r)
        this.uploading = false
        this.fileList = []
      })
    },
    handleRemove: function (file) {
      if (this.uploading) {
        this.$message.warning('文件导入中，请勿删除')
        return
      }
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    beforeUpload: function (file) {
      this.fileList = [...this.fileList, file]
      return false
    },
    handleSubmit() {
      if (this.expireTimeStatus == 'error') {
        this.$message.error('请重新选择公告有效期')
        return
      }
      if (this.validateStatus !== 'success') {
        this.validateStatus = 'success'
      }
      this.form.validateFields((error, values) => {
        if (!error && this.validateStatus === 'success') {
          this.setRoleFields()
          this.$post('gen/tbnotifyinfo', this.notity).then(res => {
            if (res.data === null) {
              this.reset()
              this.$emit('success')
              this.notity.remark1 = 0
              this.notity.remark2 = 0
            } else {
              this.$message.error(res.data.message)
            }
          })
        }
      })
    },
  }
}
</script>
<style scoped>
.components {
  width: 300px;
  margin: 30px -445px 80px -135px;
  float: left;
}
</style>
